let _debounceTimeout = null,
	_throttleRunning = false
// 防抖
const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay);
}

// 节流
const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
}

// Toast
const msg = (title = '', param = {}) => {
	if (!title) return;
	uni.showToast({
		title,
		duration: param.duration || 1500,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}
//减法函数
const accSub = (arg1, arg2) => {
	var r1, r2, m, n;
	try {
		r1 = arg1.toString().split(".")[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split(".")[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	//last modify by deeka
	//动态控制精度长度
	n = r1 >= r2 ? r1 : r2;
	return ((arg2 * m - arg1 * m) / m).toFixed(n);
}
//乘法函数
const accMul = (arg1, arg2) => {
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length;
	} catch (e) {}
	try {
		m += s2.split(".")[1].length;
	} catch (e) {}
	return (
		(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
		Math.pow(10, m)
	);
}
// 判断类型集合
const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str);
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^([a-zA-Z0-9_]){6,18}$/.test(str);
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str);
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
				/^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		case 'pwd2': //验证字符串必须包含字母、数字、_ 长度 6 - 16
			return /^(?=.*\d+)(?=.*_+)(?=.*[A-Za-z]+)[\w]{6,16}$/.test(str);
		case 'pwd1': //验证字符串必须包含字母、数字、
			return /^(?=.*\d+)(?=.*[A-Za-z]+)[\w]{8,16}$/.test(str);
		case 'pwd3': //验证字符串必须包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
			return /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?]).{6,16}$/.test(str);
		case 'bank': //银行卡首位非0，位数也不同
			return /^([1-9]{1})(\d{14}|\d{18})$/.test(str);
		default:
			return true;
	}
}
// 顶部导航栏
const setscroll = (e) => {
	if (e.scrollTop >= 45) {
		uni.setNavigationBarColor({
			backgroundColor: '#FFFFFF',
		})
	} else {
		uni.setNavigationBarColor({
			backgroundColor: 'transparent'
		})
	}
}
const navTo = (url, options = {}) => {
	throttle(() => {
		if (!url) {
			return;
		}
		if ((~url.indexOf('login=1') || options.login) && !this.$store.getters.hasLogin) {
			url = '/pages/sign/login';
		}
		uni.navigateTo({
			url
		})
	}, 300)
}
const timeFormat = (time, format = "YYYY-MM-DD hh:mm:ss", type = 1) => {
	let timestamp = time?.toString() || ''
	if (timestamp.length < 13 && type == 1) {
		timestamp = Number(timestamp.padEnd(13, '0'));
	}
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = ('0' + (date.getMonth() + 1)).slice(-2);
	const day = ('0' + date.getDate()).slice(-2);
	const hours = ('0' + date.getHours()).slice(-2);
	const minutes = ('0' + date.getMinutes()).slice(-2);
	const seconds = ('0' + date.getSeconds()).slice(-2);
	const formatresult = format.replace('YYYY', year).replace('MM', month).replace('DD',
		day).replace('hh', hours).replace('mm', minutes).replace('ss', seconds)
	return formatresult || '--'
}
// 上传图片(单张,接口也单张)
const uploadImgOne = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中...'
		});
		uni.uploadFile({
			url: Url.baseUrl + '/api/common/upload', //上传的图片的接口地址
			filePath: filePath, //chooseImage获取的本地图片路径
			name: 'file', //参数名
			header: {
				"token": uni.getStorageSync('logintoken') || ''
			},
			success: (uploadFileRes) => {
				let res = JSON.parse(uploadFileRes.data);
				if (res.code == 1) {
					uni.hideLoading()
					resolve(res.data.fullurl);
				} else {
					uni.hideLoading()
					msg(res.msg + '上传图片失败')
					reject(res.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading()
				msg(err + '上传图片失败')
				reject(err);
			}
		});
	})
}
// 选择图片
const chooseImage = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: count, // 默认最多选择9张图片
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: (res) => {
				resolve(res.tempFilePaths);
			},
			fail: (err) => {
				msg(err)
				reject(err);
			}
		});
	});
}
// 复制文字
const copyText = (text) => {
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data: text,
			showToast: false,
			success: () => {
				uni.showToast({
					title: '复制成功',
					icon: 'none'
				})
				resolve(true);
			},
			fail: (err) => {
				uni.showToast({
					title: '复制失败' + err,
					icon: 'none'
				})
				reject(err);
			}
		});
	});
}
// 打电话
const callPhoneCall = (phoneNumber) => {
	return new Promise((resolve, reject) => {
		// 使用 uni.makePhoneCall 方法拨打电话
		uni.makePhoneCall({
			phoneNumber: phoneNumber,
			success: () => {
				resolve(true);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}
//获取系统参数
const getSysInfo = () => {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: (result) => {
				const menuInfo = {};
				const statusBarHeight = result.statusBarHeight;
				// #ifdef MP
				const menuButtonInfo = uni.getMenuButtonBoundingClientRect(); //单位px
				menuInfo.menuWidth = menuButtonInfo.width; //右侧的胶囊宽度
				menuInfo.menuHeight = menuButtonInfo.height; //右侧的胶囊高度
				menuInfo.menuBorderRadius = menuButtonInfo.height / 2; //一半的圆角
				menuInfo.menuRight = result.screenWidth - menuButtonInfo.right; //右侧的胶囊距离右侧屏幕距离
				menuInfo.menuTop = menuButtonInfo.top; //右侧的胶囊顶部距离屏幕顶部的距离
				menuInfo.contentTop = statusBarHeight + 44; //内容区距离页面最上方的高度
				// #endif
				menuInfo.statusBarHeight = statusBarHeight;
				uni.setStorageSync('menuInfo', menuInfo);
				resolve(menuInfo);
			},
			fail: (error) => {
				console.error('获取系统信息失败:', error);
				reject(error);
			}
		});
	});
}
export default {
	debounce: debounce,
	throttle: throttle,
	msg: msg,
	checkStr: checkStr,
	accSub: accSub,
	accMul: accMul,
	setscroll: setscroll,
	navTo: navTo,
	uploadImgOne: uploadImgOne,
	chooseImage: chooseImage,
	timeFormat: timeFormat,
	copyText: copyText,
	callPhoneCall: callPhoneCall,
	getSysInfo: getSysInfo
}